package org.exeed.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.exeed.dao.PressContactMapper;
import org.exeed.entity.PressEntity;
import org.exeed.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PressContactService {

    @Value("${file.path}")
    private String filepath = "./temp/";

    @Value("${file.tmp}")
    private String tmpPath = "";

    private static String PRESS_CONTACT_COVER_PATH = "pressContact/";

    @Autowired
    private PressContactMapper pressContactMapper;

    @Autowired
    private SysService sysService;


    public void save(PressEntity entity) {

        PressEntity currentEntity = entity.getId() == null ? null : pressContactMapper.selectById(entity.getId());

        String url = sysService.getDefaultUrl();//静态文件路径

        String tmpFile = tmpPath + entity.getThumbnailUrl();
        if (!entity.getThumbnailUrl().contains(sysService.getDefaultUrl()) && !entity.getThumbnailUrl().isEmpty()
                && !entity.getThumbnailUrl().equals("") && FileUtil.exist(tmpFile)) {
            entity.setThumbnailUrl(entity.getThumbnailUrl());
            FileUtil.copy(tmpFile, filepath + PRESS_CONTACT_COVER_PATH + entity.getThumbnailUrl(), true);
            entity.setThumbnailUrl(url + PRESS_CONTACT_COVER_PATH + entity.getThumbnailUrl());
        }

        entity.setUpdateTime(DateUtil.current());
        if (currentEntity == null) {
            entity.setId(JWTUtils.createId());
            pressContactMapper.insert(entity);
        } else {
            pressContactMapper.updateById(entity);
        }

    }

    public Map selectList(Integer page, Integer size , String key) {
        Page<PressEntity> iPage = new Page<>(page, size);
        QueryWrapper<PressEntity> queryWrapper = new QueryWrapper<>();
        if (key != null && !key.equals("")) {
            queryWrapper.like("name", key);
        }
        queryWrapper.orderByDesc("update_time");
        IPage<PressEntity> list = pressContactMapper.selectPage(iPage, queryWrapper);
        Map<String, Object> R = new HashMap<>();
        R.put("page", page);
        R.put("size", size);
        R.put("total", list.getTotal());
        R.put("list", list.getRecords());
        return R;
    }

    public PressEntity selectById(Long id) {
        return pressContactMapper.selectById(id);
    }


    public void delete(Long id) {

        PressEntity entity = pressContactMapper.selectById(id);

        if (entity != null) {
            pressContactMapper.deleteById(entity.getId());
        }
    }

}
